#include "RunAction.h"

#include "DetectorConstruction.hh"
#include <fstream>
#include <time.h>
#include <geant4/G4ios.hh>

extern std::ofstream outFile;

RunAction::RunAction(DetectorConstruction *detector)
  : detector(detector)
{
}

RunAction::~RunAction()
{
}

void RunAction::BeginOfRunAction(const G4Run *)
{
  G4String fn = detector->getFileName();

  if (!fn.empty()) {
    outFile.open(fn.c_str(), std::ios_base::out | std::ios_base::app);
    if (outFile.is_open()) {

      // determine time and date
      time_t ts;
      time(&ts);
      struct tm *date;
      date = gmtime(&ts);
      char date_out[25];
      strftime(date_out, 25, "%Y-%m-%dT%H:%M:%S", date);


      outFile << "# ==========================================================================================================================================" << std::endl;
      outFile << "# Scintillate! (r" << REVISION << ")" << std::endl;
      outFile << "# Simulation started (GMT): " << date_out << std::endl;
      // get detector parameters
      detector->Print(outFile);
      outFile << std::endl << std::endl << std::endl;
    }
  }
}

void RunAction::EndOfRunAction(const G4Run *)
{
  if (outFile.is_open()) {
    // determine time and date
    time_t ts;
    time(&ts);
    struct tm *date;
    date = gmtime(&ts);
    char date_out[25];
    strftime(date_out, 25, "%Y-%m-%dT%H:%M:%S", date);

    outFile << std::endl << "# Simulation finished (GMT): " << date_out << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl;
    outFile.close();
  }
}


